using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace LeanUi.ImageBundle
{
    public static class PathHelper
    {
        // From = c:\some\folder\scripts\
        // To   = c:\some\folder\images\famfam
        public static string FindRelativePath(string from, string to)
        {
            string[] fromDirs = parentDirs(from);
            string[] toDirs = parentDirs(to);

            for (int i = 0; i < fromDirs.Length && i < toDirs.Length; i++)
            {
                string f = fromDirs[i];
                string t = toDirs[i];
                if (f != t)
                {
                    string restA = string.Join("/", fromDirs.Skip(i).Select(x => "..").ToArray());
                    string restB = string.Join("/", toDirs.Skip(i).ToArray());
                    return restA + "/" + restB;
                }
            }

            if (fromDirs.Length > toDirs.Length) {
                string restA = string.Join("/", fromDirs.Skip( toDirs.Length ).Select(x => "..").ToArray());
                return restA;
            }
            if (toDirs.Length > fromDirs.Length) {
                string restB = string.Join("/", toDirs.Skip( fromDirs.Length ).ToArray());
                return restB;
            }
            return "";
        }

        public static string RelativePathToFile(string basedir, string fullFileName)
        {
            return (basedir.EndsWith("\\"))
             ? fullFileName.Substring(basedir.Length)
             : fullFileName.Substring(basedir.Length+1);
        }
           
        private static string[] parentDirs(string path)
        {
            var sub = new DirectoryInfo(path);
            List<string> folders = new List<string>();
            do
            {
                folders.Add(sub.Name);
                sub = sub.Parent;
            } while (sub != null);

            folders.Reverse();
            return folders.ToArray();
        }
    }
}